class Application < Rhoconnect::Base
  class << self
    def authenticate(username,password,session)
      success = false
      base_url = "#{RAILS_SERVER_URL}/sign_in"
      params = "user[user_name]=#{username}&user[password]=#{password}"
      p "params: #{params}"
      res = RestClient.post("#{base_url}", :user => {:user_name => username, :password => password, :session => session}, :content_type => :json)
      #res = Rho::AsyncHttp.post(
      #  :url => "#{RAILS_SERVER_URL}/sign_in.json?#{params}"
      #:authentication => {
      #  :user_name => username,
      #  :password => password
      #}
      #)
      begin
        result = JSON.parse(res.body)
        p "result:  #{result}"
        #if !result.nil?

        user = result['user']
        p "user:   #{user}"
        user_name = user['user_name']
        p "user_name: #{user_name}"
        
        user_id = user['id']
          
        Store.put_value('client_id', user_id);
        success = true
      rescue Exception => ex
        p "fails"
        success = false
      end

      #user = res["body"]
      #success = !user.id.nil?
      return success
      
      #true # do some interesting authentication here...
    end

    def ans_authenticate(username,password)
      true # optionally handle rhoconnect push authentication...
    end
    
    # Add hooks for application startup here
    # Don't forget to call super at the end!
    def initializer(path)
      super
    end
    
    # Calling super here returns rack tempfile path:
    # i.e. /var/folders/J4/J4wGJ-r6H7S313GEZ-Xx5E+++TI
    # Note: This tempfile is removed when server stops or crashes...
    # See http://rack.rubyforge.org/doc/Multipart.html for more info
    # 
    # Override this by creating a copy of the file somewhere
    # and returning the path to that file (then don't call super!):
    # i.e. /mnt/myimages/soccer.png
    def store_blob(object,field_name,blob)
      super #=> returns blob[:tempfile]
    end
  end
end

Application.initializer(ROOT_PATH)

# Support passenger smart spawning/fork mode:
if defined?(PhusionPassenger)
  PhusionPassenger.on_event(:starting_worker_process) do |forked|
    if forked
      # We're in smart spawning mode.
      Store.db.client.reconnect
    else
      # We're in conservative spawning mode. We don't need to do anything.
    end
  end
end
